package net.lab1024.sa.admin.module.users.approval.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.util.ConverterUtils;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.admin.module.users.approval.dao.ConsumablesPurchaseApprovalDao;
import net.lab1024.sa.admin.module.users.approval.domain.entity.ConsumablesPurchaseApprovalEntity;
import net.lab1024.sa.admin.module.users.approval.service.ConsumablesPurchaseApprovalService;


import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
public class approvalExcelListener extends AnalysisEventListener<ConsumablesPurchaseApprovalEntity> {
    @Resource
    private ConsumablesPurchaseApprovalService consumablesPurchaseApprovalService;
    /**
     * 每隔100条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private  static final  int BATCH_COUNT = 100;

    private List<ConsumablesPurchaseApprovalEntity> cacheDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);


    public approvalExcelListener(ConsumablesPurchaseApprovalService consumablesPurchaseApprovalService){
        // 实际使用如果到了spring,请使用下面的有参构造函数
        this.consumablesPurchaseApprovalService = consumablesPurchaseApprovalService;

    }
    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(ConsumablesPurchaseApprovalEntity data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        cacheDataList.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cacheDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cacheDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }


    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！", context.readSheetHolder().getSheetName());

    }


    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        log.error("======>>>解析异常：", exception);
    }
    
    
     /**
        * 解析表头数据
        * @param headMap
        * @param context
        */
    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        log.info("表头数据：{}", ConverterUtils.convertToStringMap(headMap, context));
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cacheDataList.size());
        consumablesPurchaseApprovalService.batchInsert(cacheDataList);
        log.info("存储数据库成功！");
    }
}
